# -*- coding: utf-8 -*-
#   修改密码
# @Time    ： 2023/3/26  16:28
# @Auther  ： 徐良
# File     :  changePasswordPanel.py
import hashlib
from PySide6.QtCore import Qt, QObject, Slot
from PySide6.QtSql import QSqlQuery
from PySide6.QtWidgets import QWidget
from basePanel.ui.changePasswordUI import Ui_Form
import share.globalvar as gol
from share.dataFactory import DataFactory
from share.bioDialog import Infomation


class ChangePasswordPanel(QWidget, Ui_Form):

    def __init__(self,):
        super(ChangePasswordPanel, self).__init__()
        self.setAttribute(Qt.WA_StyledBackground)
        self.setupUi(self)
        self.setWindowFlag(Qt.WindowMaximizeButtonHint, False)
        self.setWindowFlag(Qt.WindowMinimizeButtonHint, False)
        # self.setWindowModality(2)

    @Slot()
    def on_btn_confirm_clicked(self):
        dic = gol.getValue('userDict')
        username = dic['FUserName']
        imput_currentPassword = self.edt_current.text()
        imput_newPassword = self.edt_new.text()
        imput_confirmPassword = self.edt_confirm.text()

        currentPassword = hashlib.sha256(imput_currentPassword.encode()).hexdigest()

        sql = "select FPassword,Fid from t_user where FUserName='{fn}'".format(fn=username)
        model = DataFactory.getQueryModelForSql(sql)
        fid = model.record(0).value('FId')
        password = model.record(0).value('FPassword')
        if password == currentPassword:
            if imput_newPassword != imput_confirmPassword:
                Infomation.info('新密码两次录入不一致，请重新录入')
                self.edt_new.setText('')
                self.edt_confirm.setText('')
                return
            else:
                newPassword = hashlib.sha256(imput_confirmPassword.encode()).hexdigest()
                query = QSqlQuery()
                query.prepare("Update t_user set fpassword=? where fid=?")
                query.addBindValue(newPassword)
                query.addBindValue(str(fid))
                if not query.exec():
                    Infomation.info('密码修改失败')
                    return
                else:
                    Infomation.info('密码修改成功')
                    self.close()
        else:
            Infomation.info('当前密码错误')
            return

    @Slot()
    def on_btn_cancel_clicked(self):
        print('放弃')
        self.close()


if __name__ == '__main__':
    import sys
    from PySide6.QtWidgets import QApplication
    app = QApplication(sys.argv)
    window = ChangePasswordPanel()
    window.show()
    sys.exit(app.exec_())
